package com.itwn.controller;

import com.github.pagehelper.PageInfo;
import com.itwn.entity.Cinema;
import com.itwn.result.ResponseResult;
import com.itwn.service.CinemaService;
import com.itwn.vo.CinemaVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Api("影院操作")
@RequestMapping("cinema")
@CrossOrigin
public class CinemaController {
    private CinemaService cinemaService;

    @Autowired
    public CinemaController(CinemaService cinemaService) {
        this.cinemaService = cinemaService;
    }

    @Value(value = "${img.uploadPath}")
    private String uploadPath;

    @GetMapping("/cinemaList")
    public ResponseResult<List<Cinema>> findAllCinemas(){
        ResponseResult<List<Cinema>> result = new ResponseResult<>();
        List<Cinema> cinemaList = cinemaService.findAllCinemas();
        if(cinemaList.size()>0){
            result.setCode(200);
            result.setMsg("查询成功");
            result.setData(cinemaList);
        }else{
            result.setCode(201);
            result.setMsg("查询失败");
        }
        return result;
    }

    @PostMapping("/searchCinema")
    @ApiOperation(value = "分页查询影院")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    paramType="query",name="pageNum",value="页码",
                    dataType="int",defaultValue = "1"),
            @ApiImplicitParam(
                    paramType="query",name="pageSize",value="每页多少内容",
                    dataType="int",defaultValue = "5"),
            @ApiImplicitParam(
                    paramType="query",name="name",value="影院名称",
                    dataType="String"),
            @ApiImplicitParam(
                    paramType="query",name="phone",value="影院电话",
                    dataType="String"),
            @ApiImplicitParam(
                    paramType="query",name="area",value="影院地区",
                    dataType="String")
    })
    public ResponseResult<PageInfo<Cinema>> queryByPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                                                        @RequestParam(value = "name",required = false)String name,
                                                        @RequestParam(value = "phone",required = false)String phone,
                                                        @RequestParam(value = "area",required = false)String area){

        ResponseResult<PageInfo<Cinema>> result = new ResponseResult<>();
        try {
            PageInfo<Cinema> pageInfo = cinemaService.findByCon(pageNum, pageSize, name, phone, area);
            result.setAll(200,"查询影院成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            result.setAll(201,"查询失败",null);
        }
        return result;
    }

    @PostMapping("/removeCinema")
    @ApiOperation(value = "删除影院")
    @ApiImplicitParam(
            paramType = "query",name="cinemaId",value="影院ID",
            dataType="int")
    public ResponseResult<String> removeCinema(@RequestParam(value = "cinemaId") Integer cinemaId){
        ResponseResult<String> result = new ResponseResult<>();
        try{
            int i = cinemaService.removeCinemaById(cinemaId);
            if (i==1){
                result.setAll(200,"删除成功","删除成功");
                return result;
            }else {
                result.setAll(201,"删除失败",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setAll(400,"系统异常","删除成功");
        }
        return result;
    }

    @PostMapping("/addCinema")
    @ApiOperation(value = "添加影院并上传图片")
    public ResponseResult<String> addCinema(@RequestParam(value = "fileImg")MultipartFile fileImg, Cinema cinema,HttpSession session){
        ResponseResult<String> result = new ResponseResult<>();
        //System.out.println(cinema);
        //System.out.println(fileImg);
        try{
            //执行上传图片的方法
            String cinemaImg = uploadImg(fileImg);
            //插入影院
            cinema.setCinemaImg(cinemaImg);
            int i = cinemaService.addCinema(cinema);
            if (i==1){
                result.setAll(200,"添加成功",cinemaImg);
            }else {
                result.setAll(201,"添加失败",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setAll(400,"系统异常","图片上传失败");
        }
        return result;
    }

    @PostMapping("/updateCinema")
    @ApiOperation(value = "修改影院并上传图片")
    public ResponseResult<Cinema> updateCinema(@RequestParam(value = "fileImg",required = false)MultipartFile fileImg, Cinema cinema,HttpSession session){
        ResponseResult<Cinema> result = new ResponseResult<>();
        //System.out.println(cinema);
        //System.out.println(fileImg);
        try{
            //如果传了图片，就执行上传的方法，否则不执行
            if (fileImg!=null){
                String cinemaImg = uploadImg(fileImg);
                cinema.setCinemaImg(cinemaImg);
            }

            //修改影院
            int i = cinemaService.updateCinema(cinema);
            if (i==1){
                result.setAll(200,"更新成功",cinema);
            }else {
                result.setAll(201,"更新失败",null);
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setAll(400,"系统异常",null);
        }
        return result;
    }


    //上传的方法，返回上传后的路径
    public String uploadImg(MultipartFile fileImg) throws IOException {
        //做文件上传
        //获取w文件名字 a.jpg
        String filename = fileImg.getOriginalFilename();
        //获取UUID 来替换文件的名字
        String uuid = UUID.randomUUID().toString();
        //定义文件的新名字   e.r.thhhh.hhhh.a.jpg  uuid.jpg

        //获取文件的最后一个点的下标
        int index = filename.lastIndexOf(".");
        String subFix = filename.substring(index);  // .jpg

        //新的文件名字
        filename = uuid + subFix ;
        //filename = uuid + filename.substring(filename.lastIndexOf("."));


        //获取ServletContext上传地址
        //每次启动都不一样，所以暂时放在D盘的uploadPath里
        //String realPath = session.getServletContext().getRealPath("/upload");
        //System.out.println(realPath);

        File dir = new File(uploadPath);

        //判断文件夹对象是否存在
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String cinemaImg = uploadPath+File.separator+filename;
        File f = new File(dir,filename);

        //上传文件到指定位置
        fileImg.transferTo(f);
        return cinemaImg;
    }


    @PostMapping("/searchCinemaByName")
    @ApiOperation("依照模糊关键字匹配1个影院")
    public ResponseResult<CinemaVo> searchOneCinemaByName(@RequestParam(value = "cinemaName",required = true) String cinemaName){
        ResponseResult<CinemaVo> result = new ResponseResult<>();
        List<Cinema> cinemaList = cinemaService.findOneByName(cinemaName);
        int num = cinemaList.size();
        if (num>1){

            result.setAll(202,"匹配到"+num+"条数据，请输入更详细的名称",null);
        }
        if (num==0){
            result.setAll(201,"没有查询到结果，请重新输入",null);
        }
        if (num==1){
            CinemaVo cinemaVo = new CinemaVo();
            cinemaVo.setCinemaId(cinemaList.get(0).getCinemaId());
            cinemaVo.setCinemaName(cinemaList.get(0).getCinemaName());
            result.setAll(200,"匹配成功",cinemaVo);
        }
        return result;
    }
}
